import Layer from '../../core/Layer';
import Text from '../../base/Text';

export default class extends Layer {
    constructor(canvas, style) {
        super(canvas, style);
        this.formatter = style.formatter || (value => value);
        this.max = style.max || 0;
        this.min = style.min || 0;
        this.rows = style.rows || 5;
    }

    get width() {
        const { max, min, rows } = this;
        const yAxisStep = (max - min) / (rows + 1);
        const txt = new Text(this.canvas, { ...this });
        let maxWidth = Number.MIN_VALUE;
        for (let i = 0; i <= rows; i++) {
            txt.text = this.formatter(min + i * yAxisStep);
            if (maxWidth < txt.width) {
                maxWidth = txt.width
            }
        }
        return maxWidth;
    }

    build(painter) {
        this.childs.splice(0);
        const { min, max, rows } = this;
        const yAxisStep = (max - min) / rows;
        const yStep = this.height / rows;
        for (let i = 0; i <= rows; i++) {
            const text = this.formatter(min + i * yAxisStep);
            const txt = new Text(this.canvas, {
                fontSize: this.fontSize,
                fontFamily: this.fontFamily,
                color: this.color,
                text,
                type: Text.TYPE.FILL,
                textAlign: this.textAlign,
                position: 'absolute',
            });
            if (i === 0) {
                txt.bottom = i * yStep;
            } else if (i === rows) {
                txt.bottom = i * yStep - txt.height;
            } else {
                txt.bottom = i * yStep - txt.height / 2;
            }
            if (this.textAlign === 'right') {
                txt.left = this.width;
            } else if (this.textAlign === 'left') {
                txt.left = 0;
            }
            this.addChild(txt);
        }
    }
}
